package utl.mofen.dbHandler;



import org.apache.log4j.Logger;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import utl.mofen.dbOperator.ExecuteScript;


public class OpenSQLHandler extends DBBaseHandler {
	private static final Logger logger = Logger.getLogger(OpenSQLHandler.class);
    ExecuteScript executer = new ExecuteScript();

	private void execute(JsonElement config) throws Exception
	{
		if (config == null) return;
		if (config.isJsonNull()) return;		
		JsonObject script = config.getAsJsonObject();
		
		String id = "data";
		if (script.has("id"))
		{
			id = script.get("id").getAsString();
		}		
		
		executer.clear();
		executer.setConfig(script);
		executer.executeParseSQL();
		if (isTrace)
		{
			//System.out.println(executer.getParsedSQL());
			writeTraceSQL(executer.getParsedSQL());				
		}
		String s = executer.open(true);
		
		logger.info("存入回传数据流id:" + id + ",长度" + s.length());
		
		resultKeyStream.add(id, s.getBytes("utf-8"));
	}
	
	public void doAction() throws Exception {	
		
		JsonObject json = config;

		executer.setDBOpera(this.dbOpera);
		executer.setSQLParser(this.sqlParser);	
			
		execute(json.get("script"));		
		if (json.has("list"))
		{
			JsonArray upList = json.get("list").getAsJsonArray();
			for (int i = 0; i < upList.getAsJsonArray().size(); i++) 
			{
				execute(upList.get(i));					
			}
		}

	}
}
